import xlwings as xw
import re,json,time
import pandas as pd
from hikvisionapi import Client

def 重建一张表(tabName,wb):

    if tabName  in  [i.name for i in wb.sheets] :
        wb.sheets[ tabName ].delete()
    wb.sheets.add( tabName,after = wb.sheets['配置信息'])
    return wb.sheets[tabName]


def e获取录像机通道信息():
    """
     参考文件
https://github.com/loozhengyuan/hikvision-sdk/blob/master/resources/isapi.pdf

http://192.168.6.6/ISAPI/Streaming/channels/101/picture
http://192.168.6.250/ISAPI/System/deviceInfo

http://192.168.6.250/ISAPI/ContentMgmt/InputProxy/channels
http://192.168.88.250/ISAPI/ContentMgmt/InputProxy/channels/status
    """
    wb = xw.Book.caller()
    sheet = wb.sheets['配置信息']
    cfg  =  sheet.range('A2').options( expand='table') .value
    allChannel = []
    looperr = [] # [错误编号-错误描述，出错时参数 ,错误信息]
    for i in cfg:
        dname , ip,user,pwd = i[0].strip(),i[1].strip(),i[2].strip(),  i[3].strip()
        print(ip ,user,  pwd)
        try:
            client = Client('http://{}'.format(ip),user,  pwd, timeout=1)
            thead,channels = 获取录像机通道信息(client,dname)
        except Exception as e:
            looperr.append(['net.001-无法连接都录像机','ip=={}, user=={} '.format(ip,user),e])
            continue
        allChannel = allChannel + channels
    
    
    looperr

    # 写入表格
    timeStr = time.strftime('%Y-%m-%d', time.localtime())
    wsheet =  重建一张表('摄像头通道汇总'+timeStr,wb)
    wsheet.range('A1').options( expand='table') .value = thead
    wsheet.range('A2').options( expand='table') .value = allChannel
 
    # 设置样式
    s设置单元格大小( wsheet.range((1,1),(len(allChannel),len(thead)))  )
    s设置单元格样式( wsheet.range((1,1),(1,len(thead))) )
    s设置隔行背景(wsheet)
    s首行锁定(wb,wsheet)
     
 
 
def s设置单元格大小(cell):
    
    cell.columns.autofit()

def s首行锁定(wb,sheet):
    wb.app.api.ActiveWindow.FreezePanes = False
    sheet.range((2,1)).select()#可活动的单元格
    wb.app.api.ActiveWindow.FreezePanes = True


def s设置单元格样式(cell):
    """ 可以批量 """
    cell.api.HorizontalAlignment = -4108
    cell.api.Font.Bold = True 

def s设置隔行背景(sheet):
    rowNum = sheet.used_range.last_cell.row
    rankNum = sheet.used_range.last_cell.column
    colorNum = (250,240,230)
    for i  in range(1,rowNum+1)  :
        if (i % 2)==0 :
            sheet.range((i,1),(i,rankNum) ).color = colorNum
    
def s上下去重(sheet,col=1):
    rowNum = sheet.used_range.last_cell.row
    cellVal = ''
    for i in range(1,rowNum+1):
        if cellVal == sheet.range((i,col) ).value:
            sheet.range((i,col) ).clear()
        else:
            cellVal =  sheet.range((i,col) ).value


def 获取录像机通道信息(client,name='默认'):
    """ 返回 head body """
    channelData = client.ContentMgmt.InputProxy.channels(method='get')
    channelStat = client.ContentMgmt.InputProxy.channels.status(method='get')        
    channels = []
    head = ['设备','号','名字','ip地址','协议','流号','状态']
    for r in channelData['InputProxyChannelList']['InputProxyChannel']:
        dse = r['sourceInputPortDescriptor']
        ls = [name,r['id'],r['name'],dse['ipAddress'],dse['proxyProtocol'],dse['srcInputPort']]
        channels.append(ls)
    for r,v in enumerate(channelStat['InputProxyChannelStatusList']['InputProxyChannelStatus'] ):
        channels[r].append(v['online'])
    return head,channels
    
if __name__ == "__main__":
    xw.Book("myproject.xlsm").set_mock_caller()
    
